package org.iris.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.List;

/**
 * @author zhaohaijun
 * @date 2021-12-16
 */
public class ClickHouseDemo {

    public static final String regex = "^[^{]*";
    public static Connection connection;

    public static void main(String[] args) {
        String host = "172.16.1.189";
        String port = "8123";
        initConnection(host, port);

        try {
            Statement statement = connection.createStatement();
//            statement.executeQuery("create table CIC.meta(src_ip String, dst_ip String, src_port UInt8, dst_port UInt8, proto String) Engine=Log");
            PreparedStatement pstmt = connection.prepareStatement("insert into CIC.meta (src_ip, dst_ip, src_port, dst_port, proto) values(?, ?, ?, ?, ?)");

            File dateFile = new File("C:\\Users\\13771\\Documents\\data-simple\\metadata\\ratel_oracle.log");
            List<String> dataList = FileUtils.readLines(dateFile, "UTF-8");
            for (String data : dataList) {
                data = data.trim().replaceFirst(regex, "").trim();
                JSONObject rawJson = JSONObject.parseObject(data);
                String src_ip = rawJson.getString("src_ip");
                String dst_ip = rawJson.getString("dst_ip");
                Integer src_port = rawJson.getInteger("src_port");
                Integer dst_port = rawJson.getInteger("dst_port");
                String proto = rawJson.getString("proto");

                pstmt.setString(1, src_ip);
                pstmt.setString(2, dst_ip);
                pstmt.setInt(3, src_port);
                pstmt.setInt(4, dst_port);
                pstmt.setString(5, proto);

                pstmt.addBatch();
            }

            pstmt.executeBatch();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static void initConnection(String host, String port) {
        try {
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            String url = String.format("jdbc:clickhouse://%s:%s", host, port);
            connection = DriverManager.getConnection(url);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
